<template>
  <div>
  <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
     <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
     <el-breadcrumb-item>商品管理</el-breadcrumb-item>
     <el-breadcrumb-item>商品参数</el-breadcrumb-item>
   </el-breadcrumb>
   <!-- 卡片 -->
   <el-card>
    <el-row>
      <el-col>
      <el-alert
      title="注意:只允须第三级分类设置相关参数"
       type="warning"
      show-icon
      :closable="false">
  </el-alert>
      </el-col>
    </el-row>
    <el-row>
      <span>选择商品分类:</span> 
    <!--联级选择器  -->
      <el-cascader
       v-model="goodsidarr"
      :options="goodslistinfo"
      :props="goodparamsprops"
      @change="goodsparamschange"></el-cascader>
    </el-row>
   <!-- tab 标签页 -->
   <el-tabs v-model="activeName" @tab-click="handletabClick">
    <el-tab-pane label="动态参数" name="many">
      <el-button type="primary" :disabled='goodsidarr.length === 0' @click="addparams">添加参数</el-button>
      <!-- 动态参数表格 -->
      <el-table :data='manylistdata' border stripe >
        <!-- 展开列 -->
        <el-table-column type='expand'>
          <template slot-scope='scope'>
          <!--添加标签框-->
          <el-tag
           v-for="(item,i) in scope.row.attr_vals"
           :key="i" 
           closable 
           @close="handleClose(scope.row , i)">
            {{item}}
            <!-- {{scope.row}} -->
          </el-tag>
        <el-input
        class="input-new-tag"
        v-if="scope.row.inputVisible"
        v-model="scope.row.inputValue"
         ref="saveTagInput"
         size="small"
       @keyup.enter.native="handleInputConfirm(scope.row)"
       @blur="handleInputConfirm(scope.row)"
       ></el-input>
      <el-button 
      v-else 
      class="button-new-tag" 
      size="small"
       @click="showInput(scope.row)"
       >+ New Tag</el-button>
      </template>
        </el-table-column>
        <el-table-column type='index' label='#'></el-table-column>
        <el-table-column prop='attr_name' label='参数名称'></el-table-column>
        <el-table-column label='操作'>
          <template slot-scope='scope'>
          <el-button type="primary" icon="el-icon-edit" size='mini' @click='editparams(scope.row)' >编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size='mini' @click="deleteparams(scope.row)">删除</el-button>
         </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
    <el-tab-pane label="静态属性" name="only">
      <el-button type="primary" :disabled='goodsidarr.length === 0' @click="addpropetry">添加属性</el-button>
      <!-- 静态属性表格 -->
      <el-table :data='onlylistdata' border stripe >
        <el-table-column type='index' label='#'></el-table-column>
        <el-table-column prop='attr_name' label='属性名称'></el-table-column>
        <el-table-column label='操作'>
         <template slot-scope='scope'>
          <el-button type="primary" icon="el-icon-edit" size='mini' @click='editpropetry(scope.row)' >编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size='mini' @click="deletepropetry(scope.row)">删除</el-button>
         </template>
        </el-table-column>
      </el-table>
    </el-tab-pane>
  </el-tabs>
   </el-card>
   <!-- 添加参数表格 -->
   <el-dialog
  :title=" activeName=='many'?'添加动态参数':'添加静态属性'"
  :visible.sync="adddynamicparams"
  width="50%"
  @close='clearnparams'>
  <el-form :model="addparamsfrom" :rules="rules" ref="paramsfromref"  class="demo-ruleForm">
  <el-form-item label="添加动态参数"  prop="attr_name">
    <el-input v-model="addparamsfrom.attr_name" ></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="adddynamicparams = false">取 消</el-button>
    <el-button type="primary" @click="postfrom" >确 定</el-button>
  </span>
</el-dialog>
 <!-- 编辑参数表格 -->
   <el-dialog
  :title=" activeName=='many'?'修改动态参数':'修改静态属性'"
  :visible.sync="editdynamicparams"
  width="50%"
  @close='clearnparams'>
  <el-form :model="editparamsfrom" :rules="rules" ref="paramsfromref"  class="demo-ruleForm">
  <el-form-item label="添加动态参数"  prop="attr_name">
    <el-input v-model="editparamsfrom.attr_name" ></el-input>
  </el-form-item>
  </el-form>
  <span slot="footer" class="dialog-footer">
    <el-button @click="editdynamicparams = false">取 消</el-button>
    <el-button type="primary" @click="posteditfrom" >确 定</el-button>
  </span>
</el-dialog>
  </div>
</template>

<script>
  export default {
    name:'goodsparmas',
    data () {
      return {
        goodslistinfo:[],
        goodsidarr:[],
        goodparamsprops:{
        expandTrigger: 'hover',
        value:'cat_id',
        label:'cat_name',
        children:'children'
        },
        activeName:'many',
        onlylistdata:[],
        manylistdata:[],
        //控制添加参数对话窗
        adddynamicparams:false,
        //控制修改参数对话窗
        editdynamicparams:false,
        //静态属性信息
        propetryinfo:{},
        //动态参数信息
        paramsinfo:{},
        editparamsfrom:{},
        addparamsfrom:{
             attr_name:''
        },
        rules:{
          attr_name:[
               { required: true, message: '请输入要添加的参数', trigger: 'blur' },
          ]
        }
      }
    },
    created () {
      this.addgoodsfrom()
    },
    computed: {
      cateId(){
        if(this.goodsidarr.length === 3){
          return this.goodsidarr[2]
        }
        return null
      }
    },
    methods: {
    //获取添加商品的数据
    async addgoodsfrom(){
    const res= await this.$http.get('categories')
    if(res.data.meta.status !=200){
      return  this.$message({showClose: true,message: `获取商品列表数据失败`,type: 'error'}) 
    }
      this.goodslistinfo=res.data.data
  },
  //级联选择器发生改变
  async goodsparamschange(){ 
    // console.log(this.goodsidarr)
    if(this.goodsidarr.length !==3){
      this. onlylistdata=[]
      this. manylistdata=[]
    }
    this.getparamsinfo()
  },
  // tab点击发生时间
  handletabClick(){
   this.getparamsinfo()
  },
  //获取列表参数
  async getparamsinfo(){
   const result =await this.$http.get(`categories/${this.cateId}/attributes`,
    {
      params:{sel : this.activeName}
    }
    )
    if(result.data.meta.status !=200){return this.$message({showClose: true,message: `获取商品列表数据失败`,type:'error'})}
    result.data.data.forEach(item=>{
      item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
      item.inputVisible=false
      item.inputValue=''
    }) 
    //判断数据类型存入不同数据里
    if(this.activeName==='many'){
      this.manylistdata =result.data.data
    }else{
      this.onlylistdata=result.data.data
    }
    
  },
  //显示动态参数对话框
  addparams(){
  this.adddynamicparams=true
  },
  addpropetry(){
  this.adddynamicparams=true
  },
  clearnparams(){
    this.$refs.paramsfromref.resetFields()
  },
  async postfrom(){
    const validata = await this.$refs.paramsfromref.validate()
    if(!validata) return
    const  result= await this.$http.post(`categories/${this.cateId}/attributes`,{
      attr_name:this.addparamsfrom.attr_name,
      attr_sel:this.activeName
    })
    if(result.data.meta.status !=201){return  this.$message({showClose: true,message:'添加参数失败',type:'error'})}
      this.$message({showClose: true,message: `添加参数成功！`,type: 'success'})
      this.adddynamicparams = false
     this.getparamsinfo()
  },
  //删除动态数据
  async deleteparams(userinfo){
     let comfigResult= await this.$MessageBox('此操作将永久删除该商品的动态参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
         if(comfigResult !='confirm'){
         return  this.$message('取消删除成功！');
       }
   const result =await this.$http.delete(`categories/${this.cateId}/attributes/${userinfo.attr_id}`)
   if(result.data.meta.status !=200) {
     return this.$message({showClose: true,message:'删除动态参数失败',type:'error'})
   }
   this.$message({showClose: true,message: `删除动态参数成功！`,type: 'success'})
  this.getparamsinfo()
  },
  //删除静态属性
  async deletepropetry(userinfo){
    const result =await this.$http.delete(`categories/${this.cateId}/attributes/${userinfo.attr_id}`)
    let comfigResult= await this.$MessageBox('此操作将永久删除该商品的静态属性, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err=>err)
         if(comfigResult !='confirm'){
         return  this.$message('取消删除成功！');
       }
    if(result.data.meta.status !=200) {
     return this.$message({showClose: true,message:'删除静态属性失败',type:'error'})
   }
   this.$message({showClose: true,message: `删除静态属性成功！`,type: 'success'})
  this.getparamsinfo()
  },
  //编辑静态属性
  editpropetry(userinfo){
    this.editdynamicparams=true
    this.propetryinfo=userinfo
    this.findinfopropetry()
  },
  //编辑动态参数
  editparams(userinfo){
  
  this.editdynamicparams=true
  this.paramsinfo=userinfo
  this.findinfoparams()
  },
  //查找静态数据
  async findinfoparams(){
    const result= await this.$http.get(`categories/${this.cateId}/attributes/${this.paramsinfo.attr_id}`)
    if(result.data.meta.status !=200) {return  this.$message({showClose: true,message:'查找静态属性失败',type:'error'}) }
    this.editparamsfrom=result.data.data
  },
  //查找动态属性
  async findinfopropetry(){
    const result= await this.$http.get(`categories/${this.cateId}/attributes/${this.propetryinfo.attr_id}`)
    if(result.data.meta.status !=200) {return  this.$message({showClose: true,message:'查找动态参数失败',type:'error'}) }
    this.editparamsfrom=result.data.data
  },
  //编辑参数表格功能
  async posteditfrom(){
    if(this.activeName ==='many'){
    const result =await this.$http.put(`categories/${this.cateId}/attributes/${this.paramsinfo.attr_id}`,{
    attr_name:this.editparamsfrom.attr_name,
    attr_sel:this.activeName
    })
     if(result.data.meta.status !==200){return this.$message({showClose: true,message:'修改动态参数失败',type:'error'}) }
     this.$message({showClose: true,message: `修改动态参数成功！`,type: 'success'})
     this.getparamsinfo()
    }else{
    const result =await this.$http.put(`categories/${this.cateId}/attributes/${this.propetryinfo.attr_id}`,{
    attr_name:this.editparamsfrom.attr_name,
    attr_sel:this.activeName 
    })
     if(result.data.meta.status !==200){return this.$message({showClose: true,message:'修改静态属性失败',type:'error'}) }
     this.$message({showClose: true,message: `修改静态属性成功！`,type: 'success'})
     this.getparamsinfo()  
  }
   this.editdynamicparams=false
  },
  //保存tag标签
   async  savetag(row){
    const result =await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,{
    attr_name:row.attr_name,
    attr_sel:this.activeName,
    attr_vals:row.attr_vals.join(' ')
    })
    console.log(result)
     if(result.data.meta.status !==200){return this.$message({showClose: true,message:'修改动态参数失败',type:'error'}) }
     this.$message({showClose: true,message: `修改动态参数成功！`,type: 'success'})
     this.getparamsinfo()
   },
  //标签框的失去焦点或者按下enter时都会触发
  handleInputConfirm(userinfo){
     if(userinfo.inputValue.trim().length ===0){
      userinfo.inputValue=''
      userinfo.inputVisible = false
      return
     }
    userinfo.attr_vals.push(userinfo.inputValue.trim())
    console.log( userinfo.attr_vals)
    userinfo.inputValue=''
    userinfo.inputVisible = false
    this.savetag(userinfo)
    
  },
     showInput(userinfo){
       console.log(userinfo)
    userinfo.inputVisible = true
    // 等页面渲染完以后回调里面的函数
     this.$nextTick(_ => {
       //获取input输入框绑定焦点事件
         this.$refs.saveTagInput.$refs.input.focus()      
    });
   },
   //删除标签
   handleClose(row,index){
    row.attr_vals.splice(index,1)
   }
  }
  }
</script>

<style lang="less" scoped>
.el-breadcrumb{
  margin-bottom: 10px;
}
.el-cascader{
  margin: 10px;
  width: 30%;
}
.el-form-item{
 display: flex;
 align-items: center;
}
.el-input{
  width:500px;
}
.el-button{
  margin-bottom: 10px;
}
.el-tag{
  margin: 10px;
}
.input-new-tag{
  width: 100px;
}
</style>